package com.luke.netty.sample;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @Descrtption NettyClientChannelHandler
 * @Author luke
 * @Date 2020/4/29
 **/
public class NettyClientChannelHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("-----channelActive-----");
        //连接服务器成功，连接成功后立马发消息给服务器端
        ByteBuf byteBuf = Unpooled.copiedBuffer("你好，我是客户端", CharsetUtil.UTF_8);
        ctx.channel().writeAndFlush(byteBuf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("-----channelRead-----");
        //读取到服务器端回复的消息
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("接收到服务器端的回复消息："+byteBuf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("-----exceptionCaught-----");
        ctx.close();
    }
}
